#!/bin/bash

NEW_TODOS=""

# Get the list of staged files and filter for .rb and .erb extensions
STAGED_FILES=$(git diff --cached --name-only --diff-filter=ACMR | grep -E '\.(rb|erb)$')

# Set IFS to handle filenames with spaces correctly
IFS=$'\n'

# Iterate over each staged file
for FILE in $STAGED_FILES; do
    if [ -f "$FILE" ]; then
        # Get the staged diff for the file and search for lines containing 'TODO'
        NEW_TODO=$(git diff --cached -- "$FILE" --no-ext-diff --unified=0 -a --no-prefix | \
        grep -E "^\+.*TODO" | sed -E "s/^\+.*TODO:\s*(.*)/- [ ] \1 - ${FILE//\//\\/}/" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')
        
        if [ -n "$NEW_TODO" ]; then
            # Append the new TODOs to the NEW_TODOS variable
            NEW_TODOS="${NEW_TODOS}${NEW_TODO}\n"
        fi
    else
        echo "Warning: $FILE does not exist or is not a regular file."
    fi
done

# Restore default IFS
unset IFS

# Exit if no new TODOs were found
if [ -z "$NEW_TODOS" ]; then
    exit 0
fi

# Append NEW_TODOS to README.md under a TODO section
echo -e "\n$NEW_TODOS" >> TODO.md

# Add README.md to the commit
git add TODO.md
echo -e "\n✅ TODO.md updated with new TODOs"

exit 0
